package com.zdgk.core.control.forward.network.listener;

import com.zdgk.core.control.config.ControlConfigInfo;
import com.zdgk.core.control.read.modbus.cache.DeviceRegisterCacheResult;
import com.zdgk.core.control.read.modbus.cache.entity.RuleValueEntity;
import com.zdgk.core.web.service.ConfigService;
import lombok.extern.slf4j.Slf4j;
import org.openmuc.j60870.*;
import org.openmuc.j60870.ie.IeShortFloat;
import org.openmuc.j60870.ie.InformationObject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service//SlaveHandler
public class SlaveListenerHandler implements ConnectionEventListener {

    @Resource
    private SlaveAsduHandler slaveAsduHandler;
    @Resource
    private HandelTf handelTf;

    @Resource
    private ConfigService configService;
    private ControlConfigInfo controlConfigInfo;

    @Override
    public void newASdu(Connection connection,ASdu aSdu) {
        try {
            switch (aSdu.getTypeIdentification()) {
                case C_IC_NA_1: // 总召唤命令
                    slaveAsduHandler.HANDEL_C_IC_NA_1(connection,aSdu);
                    break;
                case C_CI_NA_1: // 计数量召唤
                    slaveAsduHandler.HANDEL_C_CI_NA_1(connection,aSdu);
                    break;
                case C_CS_NA_1: // 时钟同步
                    slaveAsduHandler.HANDEL_C_CS_NA_1(connection,aSdu);
                    break;
                case C_RD_NA_1: // 读数据命令
                    slaveAsduHandler.HANDEL_C_RD_NA_1(connection,aSdu);
                    break;
                case C_SC_NA_1: // 单点命令
                    slaveAsduHandler.HANDEL_C_SC_NA_1(connection,aSdu);
                    break;
                default:
                    log.warn("未处理的ASDU类型: {}",aSdu.getTypeIdentification());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void connectionClosed(Connection connection, IOException cause) {
        log.info("{}连接断开",connection.getRemoteInetAddress());
        try{
            Info104.connectionList.remove(connection.getRemoteInetAddress().getHostAddress(),connection);
        }catch (Exception e){
            log.error("断开时错误");
            e.printStackTrace();
        }

    }

    //注意点 必须在dataTransferStateChanged之后发送，开启新线程发送，要不发送太多会阻塞导致连接断开
    @Override
    public void dataTransferStateChanged(Connection connection, boolean stopped) {
        log.info("新的连接突发{}",connection.getRemoteInetAddress());
        if(!stopped){
            try {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            handelTf.HANDEL_C_IC_NA_1_TF(connection);
                        } catch (IOException e) {
                            log.error("新的主站连接传输激活后突发失败: {}",connection.getRemoteInetAddress());
                        }
                    }
                }).start();
//                controlConfigInfo = configService.getControlKey();
//                int index = 0;
//                ArrayList<RuleValueEntity> ruleValueList = null;
//                for (Map.Entry<Integer, ArrayList<RuleValueEntity>> integerArrayListEntry : DeviceRegisterCacheResult.ruleValueMap.entrySet()) {
//                    ruleValueList = integerArrayListEntry.getValue();
//                    List<RuleValueEntity> collect1041 = ruleValueList.stream().filter(x -> "switch".equals(x.getForwardType())).collect(Collectors.toList());
//                    for (RuleValueEntity ruleValueEntity : collect1041) {
//                        Info104.sendChange(connection,ruleValueEntity,index,controlConfigInfo);
//                    }
//                    List<RuleValueEntity> collect1042 = ruleValueList.stream().filter(x -> "analog".equals(x.getForwardType())).collect(Collectors.toList());
//                    for (RuleValueEntity ruleValueEntity : collect1042) {
//                        Info104.sendChange(connection,ruleValueEntity,index,controlConfigInfo);
//                    }
//                    index++;
//                }
            } catch (Exception e) {
                log.error("新的主站连接传输激活后突发失败: {}",connection.getRemoteInetAddress());
            }
        }
    }

}
